import {createSlice,PayloadAction,Dispatch} from '@reduxjs/toolkit'
import {IAuthInialState} from '@/types/auth'
import {tranfromRightMenuToMenu,tranfromRightToRoute} from '@/utils/authutil'
import api from '@/api'
import {RouteObject} from 'react-router-dom'
import withLoadable from '@/utils/loadable'
import {push} from 'react-router-redux'
import Auth from '@/components/Auth'
const Login=withLoadable(()=>import('@/views/Login'))
const Home=withLoadable(()=>import('@/views/Home'))



/*
  initialState的类型是自定义的接口IAuthInialState
  IAuthInialState的成员menus的类型MenuProps['items']
*/
const initialState:IAuthInialState={
    menus:[],
    routes:[
        {
          path:'/login',
          element:<Login/>
        },
        {
            path:'/',
            element:<Auth><Home/></Auth>
          }
    ]
}
const authSlice=createSlice({
    name:'authNS',
    initialState,
    reducers:{
        getMenus(state:IAuthInialState,{payload}:PayloadAction<any[]>){
            state.menus=payload
        },
        getRoutes(state:IAuthInialState,{payload}:PayloadAction<any[]>){
            state.routes=payload
        }
    }
})
export const getMenusAsync=async(dispatch:Dispatch)=>{
    try {
        const result=await api.users.getAuthMenus()
        let ary=tranfromRightMenuToMenu(result.data.data)
        dispatch(getMenus(ary)) 
    } catch (error) {
        dispatch(push('/login'))
    }
  
}
export const getRoutesAsync=async(dispatch:Dispatch,getState:any)=>{
   
    try {
        const result=await api.users.getAuthMenus()
        const routes:Array<RouteObject>=[
            {
              path:'/login',
              element:<Login/>
            },
            {
                path:'/',
                element:<Auth><Home/></Auth>
            }
        ]
        if(result){
            if(result.data.data){
                let ary=tranfromRightToRoute(result.data.data)
                routes[1].children=ary
                dispatch(getRoutes(routes))    
            }else{
                dispatch(getRoutes(routes)) 
            }
        }
    } catch (error) {
        dispatch(push('/login'))
    }
}
export const {getMenus,getRoutes}=authSlice.actions
export default authSlice.reducer
